<?php

namespace app\controller;

use app\BaseController;
use app\model\Bom;
use app\model\Dept;
use think\facade\Db;
use app\model\Config;
use think\facade\View;
use app\model\Menu;
use app\model\UserQywx;
use app\model\UserRole;
use app\model\UserLog;
use app\model\User;
use app\model\Role;
use app\model\Items;
use app\model\Recharge;
use app\model\AccRefund;
use app\model\ReturnedMoney;
use app\model\Customer;
use app\model\ItemConsume;
use app\model\OpAccount;
use app\model\Order;
use think\facade\Request;
use app\model\AccTransfer;
use app\model\OperateYeji;

class Index extends BaseController
{
    
    public function index()
    {
        
        $this->finance_msg();
        return view();
    }

    public function welcome()
    {
        
        $this->sy_user();
        //$this->get_welcome_info();
        return view();
    }

    public function init(Menu $menu,OperateYeji $OperateYeji)
    {
        $data = []; 
        $data['homeInfo'] = [
            "title" => "首页",
            "href" => "welcome"
        ];
        // 任务完成度
        $t = strtotime(date('Y-m',time()));
        $t2 = strtotime(" +1 month -1 day");
        $wh[] = ['time','between',[$t,$t2]];
        $wh[] = ['operate_id','=',session('uid')];
        $rw = OperateYeji::where($wh)->find();
        if($rw){
            $xh = $OperateYeji->get_xiaohao_sum(session('uid'),$t,$t2);
            $lv = ($xh/$rw['yeji'])*100;
            $lv = round($lv,2);
        }else{
            $lv = 0;
        }
        $name = session('info.username');
        if(strripos($name,'-')){
            $name = substr($name, strrpos($name,'-')+1);
        }
        $data['logoInfo'] = [
            "href" => "/",
            "title" => $name?$name:"牧唐技术",
            "image" => session('info.avatar')?session('info.avatar'):"/static/images/logo.png",
            'lv'=> $lv,
        ]; 
        $data['menuInfo'] = $menu->getMenuTree();
        
        // 权限限定菜单
        if (session('info.role_id')) {
            $uid = \session('info.role_id');
            $r = Role::find($uid);
            if ($r) {
                $menus = [];
                foreach ($data['menuInfo'] as $menu) {
                    if (in_array($menu['id'], $r->rules))
                        $menus[] = $menu;
                }
                $data['menuInfo'] = $menus;
            }
        }
        
        return json($data);
    }
    //获取任务进度
    function get_re_jd(OperateYeji $OperateYeji){
        $t = strtotime(date('Y-m',time()));
        $t2 = strtotime(" +1 month -1 day");
        $wh[] = ['time','between',[$t,$t2]];
        $wh[] = ['operate_id','=',session('uid')];
        $rw = OperateYeji::where($wh)->find();
        $xh = $OperateYeji->get_xiaohao_sum(session('uid'),$t,$t2);
        $lv = ($xh/$rw['yeji'])*100;
        $lv = round($lv,2);
        return $lv;
    }

    public function cache_clear()
    {
        cache()->clear();
        return ['code'=>1, 'msg'=>'服务端清理缓存成功'];
    }

    public function no_permission()
    {
        return view();
    }
    //api授权
    public function no_impower()
    {
        return view();
    }
    //登录
    public function login()
    { 
       
        if(Request::host() == 'oa.d'){
            $id = 2;
            $qywx_id = 2;
            session('uid',$id);
             $UserInfo = User::where(['qywx_id' => $qywx_id])->find();
             session('info',$UserInfo);
        }
        $UserLog = new UserLog();
        if(request()->isPost() && input('t')=='json'){
            $data = input('post.');
            $wh[] = ['username','=',$data['username']];
            $wh[] = ['password','=',$data['password']];
            $UserInfo = User::where($wh)->find();
            if(!empty($UserInfo)){
                // 更新用户 最后登录时间 及 IP
                $UserInfo->save(['last_login_ip' => request()->ip(), 'last_login_time' => time()]);

                session('info',$UserInfo);
                session('uid',$UserInfo['id']); 
                $UserLog->write(1);
                return json(['msg' => '登录成功', 'code' => 1]);
                // return redirect('Index/index');
            }else{
                return json(['msg' => '登录失败', 'code' => 0]);
            }
        }else{
            if (!empty(session('uid'))) { 
                return redirect('/index');
            }
            return view('', ['qywx' => config('qywx')]); 
        }
        
    }
    //微信登录
    public function qywx_login(UserQywx $UserQywx, UserLog $UserLog)
    {
        $code = input('code');
        $state = input('state');
        $appid = input('appid');

        // 获取/更新 access_token
        $access_token = qywx_token();

        // 是否企业微信成员
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=$access_token&code=$code";
        $res = json_decode(http_gett($url)['content']);
        if (empty($res->UserId)) {
            return view('', ['msg' => '登录失败或已失效']);
        }

        // 获取用户信息
        $user_id = $res->UserId;
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=$access_token&userid=$user_id";
        $res = json_decode(http_gett($url)['content'], 1);
        if (!empty($res['status']) && $res['status'] != 1) {
            switch ($res['status']) {
                case 2:
                    $msg = '此账号已禁用';
                    break;
                case 3:
                    $msg = '此账号未激活';
                    break;
                case 5:
                    $msg = '此账号已退出企业';
                    break;
            }
            return view('', ['msg' => $msg]);
        }

        $data = array_map(function ($a) {
            return is_array($a) ? json_encode($a) : $a;
        }, $res);

        $UserQy = UserQywx::where(['userid' => $data['userid']])->find();
        if (empty($UserQy)) {
            $UserQy = UserQywx::create($data);
        } else {
            $UserQy->save($data);
        }

        // 用户信息
        $UserInfo = User::where(['qywx_id' => $UserQy->id])->find();
        if (empty($UserInfo)) {
            $UserInfo = User::create([
                'qywx_id' => $UserQy->id,
                'username' => $data['name'],
                'gender' => $data['gender'],
                'mobile' => $data['mobile'],
                'position' => $data['position'],
                'avatar' => $data['thumb_avatar'],
                'status' => 1,
            ]);
        }

        // 更新用户 最后登录时间 及 IP
        $UserInfo->save(['last_login_ip' => request()->ip(), 'last_login_time' => time()]);

        session('uid', $UserInfo->id);
        session('info', $UserInfo);
        // 获取角色ids
        session('role_ids', $UserInfo->role_ids());
        $UserLog->write(1);
        return redirect('/index');
    }
    //退出
    public function logout(UserLog $UserLog)
    {
        if (session('uid')) {
            session('uid', NULL);
            $UserLog->write(2);
        }
        return redirect('/login');
    }

    public function is_login(UserLog $UserLog)
    {
        if (empty(session('uid'))) {
            $UserLog->write(3);
            return json(['msg' => '登录失效', 'code' => 1]);
        }
        return json(['code' => 0]);
    }

    /**
     * 测试用 无需登录
     */
    public function test()
    {
        // $charge = \number_format(1988123498);

        // $t = date('Y-m-d H:i:s',time());
        // //$msg = "***您有新的消息*** \n类型：`客户打款`\n名称: cs \n打款金额：3423\n时间：".date('Y-m-t H:i:s',time())."\n请您尽快处理。";
        // //$msg .= ">[goto](http://oa.mutangtech.com)";
        // $msg = "***您有新的消息*** \n 类型：`打款` \n 客户：<font color=\"info\">ddd</font>  \n 金额：<font color=\"comment\">345</font>  \n 时间：45634 \n 请您尽快处理。 \n";
        // $s = qywx_send(2, $msg);
        // dump($s);
        //get_msg_info(5,2,'dfg',3435);
        // $s = get_xh_rebates(345,821,1572.37);
        // dump($s);
        // $dk =  zhb_cny(10000,28);
        // $s = cny_profit(10000,10,28);
        // dump($dk);
        // dump($s);
        
    }
    
    

    public function r()
    {
        return [User, Role];
    }
    
    /*
     * 财务消息提醒
     *   */
    public function finance_msg(){ 
        if(request()->isPost()&& input('t')=='json' && session('info.role_id') == 21){
           
            //客户打款 出纳
            $w2['type'] = 1;
            $w2['status'] = 0;
            $w2['is_paid'] = 0;
            $arr['cashier_cu_re'] = Recharge::where($w2)->count('id');
            
            //客户退款 
            $t = strtotime(date('Y-m-d',time())) - 518400;
            $w4[] = ['type','=',3];
            $w4[] = ['status','=',0];
            $w4[] = ['is_paid','=',0];
            $w4[] = ['create_time','<=',$t];
            $arr['cashier_cu_refund'] = Recharge::where($w4)->count('id');
           
            //账户充值  出纳
            $w6['type'] = 2;
            $w6['status'] = 0;
            $w6['is_paid'] = 0;
            $arr['cashier_acc_re'] = Recharge::where($w6)->count('id');
            
            //账户退款  出纳
            $w8['type'] = 4;
            $w8['status'] = 0;
            $arr['cashier_acc_refund'] = Recharge::where($w8)->count('id');
            
            //回款确认 出纳
            $w10['status'] = 2;
            $arr['cashier_cu_return_money'] = ReturnedMoney::where($w10)->count('id');
            
            //销售订单
            $w11['is_jiesuan'] = 0;
            $arr['cashier_order'] = Order::where($w11)->count('id'); 

            //账户转账
            $w12[] = ['status','=',1];
            $arr['cashier_transfer'] = AccTransfer::where($w12)->count('id');

            $arr['count'] = 0;
            if($arr['cashier_transfer']>0 || $arr['cashier_cu_re']>0 || $arr['cashier_cu_refund']>0 || $arr['cashier_acc_re']>0 || $arr['cashier_acc_refund']>0 || $arr['cashier_cu_return_money']>0){
                $arr['count'] = 1;
                return json(['msg' => '', 'code' => 1,'data'=>$arr]);
            }else{
                return json(['msg' => '没有新的消息', 'code' => 0]);
            }
          
        }else{
            return json(['msg' => '4444', 'code' => 0]);
        }
        
    }
    
    /*
     * 首页
     *   */
    public function get_welcome_info(){
        //客户打款
        $w1[] = ['type','=',1];
        $w1[] = ['status','=',1];
        $arr['amount'] = Recharge::where($w1)->whereMonth('create_time')->sum('amount');
        $arr['amount'] = number_format(floatval($arr['amount']), 2);
        $arr['today_amount'] = Recharge::where($w1)->whereDay('create_time')->sum('amount');
        $arr['today_amount'] = number_format(floatval($arr['today_amount']), 2);
        //客户退款
        $w2[] = ['type','=',3];
        $w2[] = ['status','=',1];
        $arr['return_amount'] = Recharge::where($w2)->whereMonth('create_time')->sum('amount');
        $arr['return_amount'] = number_format(floatval($arr['return_amount']), 2);
        $arr['today_return_amount'] = Recharge::where($w2)->whereDay('create_time')->sum('amount');
        $arr['today_return_amount'] = number_format(floatval($arr['today_return_amount']), 2);
        //账户充值
        $w3[] = ['type','=',2];
        $w3[] = ['status','=',1];
        $arr['currency'] = Recharge::where($w3)->whereMonth('create_time')->sum('practical_currency');
        $arr['currency'] = number_format(floatval($arr['currency']), 3);
        $arr['today_currency'] = Recharge::where($w3)->whereDay('create_time')->sum('practical_currency');
        $arr['today_currency'] = number_format(floatval($arr['today_currency']), 3);
        //账户退款
        $w4[] = ['status','=',2];
        $arr['return_currency'] = AccRefund::where($w4)->whereMonth('create_time')->sum('r_currency');
        $arr['return_currency'] = number_format(floatval($arr['return_currency']), 3);
        $arr['today_return_currency'] = AccRefund::where($w4)->whereDay('create_time')->sum('r_currency');
        $arr['today_return_currency'] = number_format(floatval($arr['today_return_currency']), 3);
        
        //客户数量
        $arr['customer'] = Customer::count('id');
        $arr['month_customer'] = Customer::whereMonth('create_time')->count('id');
        $arr['today_customer'] = Customer::whereDay('create_time')->count('id');
        
        //账户消耗
        $arr['consume'] = ItemConsume::whereMonth('time')->sum('currency');
        $arr['consume'] = number_format(floatval($arr['consume']), 3);
        $arr['today_consume'] = ItemConsume::whereDay('time')->sum('currency');
        $arr['today_consume'] = number_format(floatval($arr['today_consume']), 3);
        
        View::assign('info',$arr);
    }

    //开户进度玫瑰图表数据
    public function account_jindu(){
        if(request()->isPost() && input('t')=='json'){
            //所有账户的数量
            $count = OpAccount::count('id');
            //开户中的数量
            $w1[] =['jindu','in','1,6'];
            $w2[] = ['status','=',1];
            $arr[] = OpAccount::where($w1)->count('id');
            //过素材阶段一的数量
            $w2[] =['jindu','=',3];
            $w2[] = ['status','=',1];
            $arr[] = OpAccount::where($w2)->count('id');
            //过素材阶段二和 过素材 的数量
            $w3[] =['jindu','in','2,4'];
            $w3[] = ['status','=',1];
            $arr[] = OpAccount::where($w3)->count('id');
            //备户完成未投递 的数量
            $w[] = ['is_deliver','=',1];
            $w[] = ['is_finish','=',0];
            $ids = Items::where($w)->column('op_account_id');
            $w4[] =['jindu','=',5];
            $w4[] =['id','not in',$ids];
            $w4[] = ['status','=',1];
            $arr[] = OpAccount::where($w4)->count('id');
            //禁用账户
            $w5[] = ['status','=',0];
            $arr[] = OpAccount::where($w5)->count('id');
            //$arr[] = 10;
            //投递中的数量
            $arr[] = count($ids);
            return json(['msg' => '', 'code' => 1,'data'=>$arr]);
        }else{
            return json(['msg' => '没有数据', 'code' => 0,'data'=>[]]);
        }
           
    }
    //总消耗 （年:1，月:2，日:3）item_consume
    function get_consume_info(){
        if(request()->isPost() && input('t')=='json'){
            $t = input('post.time',3);
            if($t == 1){
               
            }elseif ($t == 2){
                $m = $this->get_month();
                for ($i=0;$i<count($m);$i++){
                    $arr['x'][] = $m[$i];
                    $w[] = ['id','>',0];
                    $arr['y'][] = ItemConsume::where($w)->whereMonth('time', $m[$i]) ->sum('currency');
                }
                $arr['text'] = '最近12个月消耗';
                return json(['msg' => '', 'code' => 1,'data'=>$arr]);
            }elseif ($t == 3){
                $tt = $this->get_time();
                for ($i=0;$i<count($tt);$i++){
                    $arr['x'][] = date("m-d",$tt[$i]);
                    $arr['y'][] = $this->get_day_consume($tt[$i]);
                }
                $arr['text'] = '最近30天消耗';
                return json(['msg' => '', 'code' => 1,'data'=>$arr]);
            }
            
        }
    }

    //获取最近30天时间
    function get_time(){
        $t1 = strtotime(date("Y-m-d",strtotime("-30 day"))) - 86400;
        for ($i=0;$i<30;$i++){
            $t[] = $t1 += 86400;
        }
        return $t;
    }
    //获取最近12个时间
    function get_month(){
         for ($i=11;$i>=0;$i--){
            $t[] = date("Y-m",strtotime("-$i month"));
         }
        return $t;
    }
    //获取每天的消耗
    function get_day_consume($t){
        $s = $t.','.($t+86400);
        //$w[] = ['time','between',$s];
        $w[] = ['time','=',$t];
        $n = ItemConsume::where($w)->sum('currency');
        return $n;
    }

    //消耗排行榜
    public function consume_top(){
        if(request()->isPost() && input('t')=='json'){
            $type = input('post.type',1);
            if($type == 1){
                //获取左天的消耗
                $t = strtotime(date("Y-m-d",strtotime("-1 day")));
                $t2 = $t+86399;
                $arr['text'] = '昨天消耗排行';
            }elseif ($type == 2){
                $w=date('w');//获取当前周的第几天 周日是 0 周一到周六是1-6
                $beginLastweek=strtotime('-'.($w ? $w-1 : 6).' day');//获取本周开始日期，如果$w是0是周日:-6天;其它:$w-1天
                $cur_monday=date('Y-m-d',$beginLastweek);
                $s=date('Y-m-d',strtotime("$cur_monday -7 day"));
                $e=date('Y-m-d',strtotime("$s +6 days"));
                $t = strtotime($s);
                $t2 = strtotime($e)+86399;
                $arr['text'] = '上周消耗排行';
            }elseif ($type == 3){
                $t = mktime(0, 0 , 0,date("m")-1,1,date("Y"));
                $t2 = mktime(23,59,59,date("m") ,0,date("Y"));
                $arr['text'] = '上月消耗排行';
            }elseif($type == 4){
                //自定义时间消耗排行
                $time = input('post.times');
                if($time == 0){
                    $t = strtotime(date("Y-m-d",strtotime("-1 day")));
                    $t2 = $t+86399;
                    $arr['text'] = '昨天消耗排行';
                }else{
                    $arr = explode('&', $time);
                    $t = strtotime($arr[0]);
                    $t2 = strtotime($arr[1])+86399;
                    $arr['text'] = $time.'消耗排行';
                }
                
            }
            $wh[] = ['role_id','=',18];
            $wh[] = ['status','=',1];
            $list = User::field('id,username')->where($wh)->select();
            foreach ($list as $k=>$v){
                $name = preg_replace('/牧唐-运营助理-/','',$v['username']);
                if(strlen($name)>9){
                    $name = preg_replace('/牧唐-运营-/','',$v['username']);
                }
                $arr['x'][] = $name;
                $arr['y'][] = $this->get_run_consume($v['id'],$t,$t2);
            }
            
            
            return json(['msg' => '', 'code' => 1,'data'=>$arr]);
        }
        
        
    }

    //获取需要排名的运营同学
    function get_run_consume($id,$t1,$t2){
        $s = $t1.','.$t2;
        $w[] = ['time','between',$s];
        //$w[] = ['time','=',$t];
        $w[] = ['operation_id','=',$id];
        $n = ItemConsume::where($w)->sum('currency');
        return $n;
    }


    //首页
    function sy_user(){
        $info =  session('info');
        $dept_name = Db::name("dept")->where('id',$info['dept_id'])->value("name");
        $data['username'] = $info['username'];
        $data['avatar'] = $info['avatar'];
        $data['dept_name'] = $dept_name;
        if(empty($info['join_time'])){
            $data['join_time'] = '--';
            $data['day'] = '--';
        }else{
            $data['join_time'] = date('Y-m-d',$info['join_time']);
            $data['day'] = intval((time() - $info['join_time'])/60/60/24);
        }
        if(empty($info['birthday'])){
            $data['sr'] = '--';
        }else{
            $sr = date('m-d',$info['birthday']);
            $sr = strtotime(date('Y').'-'.$sr) - time();
            if($sr > 86400 ){
                $data['sr'] = intval($sr/60/60/24);
            }elseif($sr > 0 && $sr < 86400){
                $data['sr'] = '生日快乐';
            }else{
                $data['sr'] = '已过生日';
            }
        }
        
        
        // 媒介和运营的账户数量或客户数量
        if($info['dept_id'] == 2){
            $w1[] = ['operate_id','=',$info['id']];
            $w1[] = ['is_banned','=',1];
            $data['acc_num'] = OpAccount::where($w1)->count('id');
            $data['consume'] = ItemConsume::where('operation_id',$info['id'])->sum('currency');
            $data['consume'] = number_format($data['consume'],2);
            $wh[] = ['operation_id','=',$info['id']];
            $t1 = strtotime(date("Y-m-d",strtotime("-1 day")));
            $t2 = $t1 + 86399;
            $wh[] = ['time','between',[$t1,$t2]];
            $data['yesterday'] = ItemConsume::where($wh)->sum('currency');
            $data['yesterday'] =round($data['yesterday'],2);
        }else{
            $data['acc_num'] = '';
            $data['consume'] = '';
            $data['yesterday'] = '';
        }
        if($info['dept_id'] == 4){
            $data['cu_num'] = Customer::where('user_id',$info['id'])->count('id');
        }else{
            $data['cu_num'] = '';
        }
        // 公司寄语
        $data['company_wishes'] = C('company_wishes');
        $data['company_ana'] = explode('*',C('company_ana'));
        View::assign('info',$data);
        // dump($data);
       
    }
    

   



















}
